/**
 * 
 */
package com.wolfpire.system.dao.impl;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.wolfpire.system.common.base.dao.impl.BaseHibernateDao;
import com.wolfpire.system.dao.RoleAuthorityRelationDao;
import com.wolfpire.system.model.RoleAuthorityRelation;

/**
 * @author lihd
 *
 */

@Repository("roleAuthorityRelationDao")
public class RoleAuthorityRelationDaoImpl extends
		BaseHibernateDao<RoleAuthorityRelation, Long> implements
		RoleAuthorityRelationDao {

	@Override
	public void relate(Long roleId, Long[] authorityIds) {
		//先删除后绑定
		this.deleteByRoleId(roleId);
		if (!ArrayUtils.isEmpty(authorityIds)) {
			for (Long authorityId : authorityIds) {
				RoleAuthorityRelation ra = new RoleAuthorityRelation(roleId, authorityId);
				this.saveOrUpdate(ra);
			}
		}
	}

	@Override
	public void relate(Long roleId, List<Long> authorityIds) {
		// TODO Auto-generated method stub
		//先删除后绑定
		this.deleteByRoleId(roleId);
		if (CollectionUtils.isNotEmpty(authorityIds)) {
			Session session = this.getSession();
			int size = authorityIds.size();
			for (int i = 0; i < size; i++) {
				RoleAuthorityRelation ur = new RoleAuthorityRelation(roleId, authorityIds.get(i));
				session.save(ur);
				if ((i + 1) % 50 == 0) {
					session.flush();
					session.clear();
				}
			}
		}
	}

	public void deleteByRoleId(Long roleId) {
		String executeSql = "DELETE FROM t_sm_role_authority WHERE role_id = ?";
		this.executeSql(executeSql, roleId);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<RoleAuthorityRelation> getRARealation(Long roleId) {
		Criteria c = createCriteria().add(Restrictions.eq("roleId", roleId)).add(Restrictions.isNotNull("authorityId"));
		return c.list();
	}
	
}
